package cn.npe2.scaffolding.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * excel工具类
 *
 * @author: yic
 * @since: 2021-03-08 10:48
 **/

@Slf4j
@UtilityClass
public class ExcelUtil {

    /**
     * 数据导出
     *
     * @param response
     * @param fileName
     * @param cls
     * @param dataList
     * @throws IOException
     */
    public void download(HttpServletResponse response, String fileName,
            Class cls, List dataList) throws IOException {
        // response.setContentType("application/vnd.ms-excel");
        response.setContentType(
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fname = URLEncoder.encode(fileName, "utf-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-disposition",
                "attachment;filename=" + fname + ExcelTypeEnum.XLSX.getValue());
        LongestMatchColumnWidthStyleStrategy longestMatchColumnWidthStyleStrategy =
                new LongestMatchColumnWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), cls)
                .sheet("sheet1")
                .registerWriteHandler(longestMatchColumnWidthStyleStrategy)
                .doWrite(dataList);
        response.flushBuffer();
    }

    /**
     * 数据分页导出
     *
     * @param response
     * @param dataMap
     * @param classMap
     * @param fileName
     * @throws IOException
     */
    public void downloadMultiPage(HttpServletResponse response, Map<String, List> dataMap,
            Map<String, Class> classMap, String fileName) throws IOException {

        // response.setContentType("application/vnd.ms-excel");
        response.setContentType(
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fname = URLEncoder.encode(fileName, "utf-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-disposition",
                "attachment;filename=" + fname + ExcelTypeEnum.XLSX.getValue());
        int i = 0;
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        for (String sheetName : dataMap.keySet()) {
            List dataList = dataMap.get(sheetName);
            Class cls = classMap.get(sheetName);
            WriteSheet writeSheet1 = EasyExcel.writerSheet(i, sheetName).head(cls).build();
            excelWriter.write(dataList, writeSheet1);
            i++;
        }
        excelWriter.finish();
        response.flushBuffer();
    }

    /**
     * 模板下载
     *
     * @param fileName 文件名称
     * @param clazz    excel写入参数类
     * @param list     填充数据
     * @param response 响应对象
     * @param <T>
     */
    public <T> void downloadTemplate(String fileName, Class<T> clazz, List<T> list,
            HttpServletResponse response) throws Exception {
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            EasyExcel.write(response.getOutputStream(), clazz)
                    .sheet(fileName).doWrite(list);
        } catch (IOException e) {
            log.error("下载失败报错方法：{}", e.getStackTrace()[0].getMethodName());
            throw new Exception("模板下载失败");
        }
    }

}
